<template>
	<view class="page-content">
		<view class="user-page-header">
			<view class="drawer-trigger" :style="topBarStyle">
				<text class="userIconFont icon-cbl" @click="showDrawer = true"></text>
			</view>
			<view class="man-add" :style="topBarStyle">
				<text class="userIconFont icon-xfk"></text>
				<view class="man-add-xfk">
					<navigator url="/pages_sub/user/visitor/visitor" hover-class="none">
						新访客
					</navigator>
				</view>
				{{userInfo.visitNumber||0}}人
			</view>
		</view>

		<UserInfo :userInfo="userInfo" :albumList="albumList" :tagList="tagList" :storeList="storeList"
			:showOther="false" :showGuide="true" @updateData="getUserInfo"></UserInfo>
		<Tabbar :tabbar-index="4" @updateTabbar="updateTabbar"></Tabbar>
		<PublishPopup :show="showPublishPopup" @close="showPublishPopup = false" />

		<u-popup :show="showDrawer" :mode="popupMode" @close="showDrawer = false" :safeAreaInsetBottom="true" round="10"
			:customStyle="{width: '450rpx'}">
			<view class="new-drawer-content">
				<view class="custom-cell-group">
					<!-- <view class="custom-cell" @click="navigateTo('/pages_sub/user/my-drafts/my-drafts')">
						<view class="cell-left">
							<text class="userIconFont icon-wdcg cell-icon"></text>
							<text class="cell-title">我的草稿</text>
						</view>
						<uni-icons type="right" size="16" color="#969799"></uni-icons>
					</view> -->
					<view class="custom-cell" @click="navigateTo('/pages_sub/user/my-collections/my-collections')">
						<view class="cell-left">
							<text class="userIconFont icon-wdsc cell-icon" style="font-size: 25px;"></text>
							<text class="cell-title">我的收藏</text>
						</view>
						<uni-icons type="right" size="16" color="#969799"></uni-icons>
					</view>
					<view class="custom-cell" @click="navigateTo('/pages_sub/placeholder/history')">
						<view class="cell-left">
							<text class="userIconFont icon-llls cell-icon"></text>
							<text class="cell-title">浏览历史</text>
						</view>
						<uni-icons type="right" size="16" color="#969799"></uni-icons>
					</view>
					<view class="custom-cell" @click="navigateTo('/pages_sub/placeholder/comments')">
						<view class="cell-left">
							<text class="userIconFont icon-wdpl cell-icon" style="font-size: 19px;"></text>
							<text class="cell-title">我的评论</text>
						</view>
						<uni-icons type="right" size="16" color="#969799"></uni-icons>
					</view>
				</view>

				<view class="separator"></view>

				<!-- <view class="custom-cell-group">
					<view class="custom-cell" @click="navigateTo('/pages_sub/placeholder/orders')">
						<view class="cell-left">
							<text class="userIconFont icon-wddd cell-icon"></text>
							<text class="cell-title">我的订单</text>
						</view>
						<uni-icons type="right" size="16" color="#969799"></uni-icons>
					</view>
					<view class="custom-cell" @click="navigateTo('/pages_sub/placeholder/wallet')">
						<view class="cell-left">
							<text class="userIconFont icon-wdqb cell-icon"></text>
							<text class="cell-title">我的钱包</text>
						</view>
						<uni-icons type="right" size="16" color="#969799"></uni-icons>
					</view>
				</view> -->

				<view class="separator"></view>

				<view class="custom-cell-group">
					<view class="custom-cell" @click="navigateTo('/pages_sub/user/qrcode/qrcode','my-qrcode')">
						<view class="cell-left">
							<text class="userIconFont icon-wdeem cell-icon"></text>
							<text class="cell-title">我的二维码</text>
						</view>
						<uni-icons type="right" size="16" color="#969799"></uni-icons>
					</view>
					<view class="custom-cell" @click="navigateTo('/pages_sub/user/settings/settings')">
						<view class="cell-left">
							<text class="userIconFont icon-sz cell-icon"></text>
							<text class="cell-title">设置</text>
						</view>
						<uni-icons type="right" size="16" color="#969799"></uni-icons>
					</view>
				</view>

				<view style="flex-grow: 1;"></view>

				<view class="drawer-bottom-actions">
					<view class="action-item" @click="navigateTo('/pages_sub/placeholder/customer-service')">
						<text class="userIconFont icon-service"></text>
						<text class="action-text">我的客服</text>
					</view>
					<view class="action-item" @click="onScanCode">
						<text class="userIconFont icon-scan"></text>
						<text class="action-text">扫一扫</text>
					</view>
					<view class="action-item" @click="navigateTo('/pages_sub/user/switch-account/switch-account')">
						<text class="userIconFont icon-switch-account"></text>
						<text class="action-text">切换账号</text>
					</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import Tabbar from "@/components/tabbar/tabbar.vue"
	import PublishPopup from '@/components/PublishPopup/PublishPopup.vue';
	import UserInfo from "@/components/user-info/user-info.vue"
	import {
		getUser,
		getOwnPostImages
	} from '@/request/api.js'
	import processScanResult from '@/utils/scan-processor.js';
	export default {
		components: {
			Tabbar,
			PublishPopup,
			UserInfo
		},
		data() {
			return {
				showPublishPopup: false, // 控制弹窗的显示与隐藏
				userInfo: this.$store.state.userInfo || null,
				albumList: [],
				tagList: [],
				storeList: [],
				showDrawer: false,
				popupMode: 'right',
			}
		},
		onReady() {},
		onLoad() {
			// 监听全局弹窗事件
			uni.$on('togglePublishPopup', this.handleTogglePublishPopup);
			// #ifdef MP-WEIXIN
			this.popupMode = 'left'
			// #endif
		},
		onUnload() {
			// 移除事件监听，防止内存泄漏
			uni.$off('togglePublishPopup', this.handleTogglePublishPopup);
		},
		onHide() {
			// 当页面被隐藏时（例如切换Tab），强制关闭弹窗
			this.showPublishPopup = false;
		},
		onShow() {
			this.initData()
		},
		onPullDownRefresh() {
			this.initData()
			setTimeout(function() {
				uni.stopPullDownRefresh();
			}, 1000);
		},
		computed: {
			topBarStyle() {
				// #ifdef APP-PLUS 
				return `top: ${uni.getSystemInfoSync().statusBarHeight}px;`;
				// #endif

				// 在非小程序平台或计算完成前，返回一个空字符串
				return '';
			}
		},
		onBackPress(options) {
			// 优先关闭发布弹窗
			if (options.from === 'backbutton' && this.showPublishPopup) {
				this.showPublishPopup = false;
				return true;
			}

			return false;
		},
		methods: {
			initData() {
				this.getUserInfo()
			},
			updateTabbar() {},
			getUserInfo() {
				getUser().then((res) => {
					if (res.data && res.data.data) {
						this.userInfo = res.data.data
						this.$store.commit('setUserInfo', res.data.data);
						this.tagList = this.userInfo.topicsList || []
						this.storeList = this.userInfo.storeList || []
					} else {
						this.userInfo = this.$store.state.userInfo || {};
						this.tagList = (this.$store.state.userInfo && this.$store.state.userInfo.topicsList) || [];
						this.storeList = (this.$store.state.userInfo && this.$store.state.userInfo.storeList) ||
					[];
					}
				}).catch(err => {
					this.userInfo = this.$store.state.userInfo || {};
					this.tagList = (this.$store.state.userInfo && this.$store.state.userInfo.topicsList) || [];
					this.storeList = (this.$store.state.userInfo && this.$store.state.userInfo.storeList) || [];
				})
				let params = {
					userId: this.$store.state.userInfo.userId,
					fellowsIds: [],
					pageNum: 1,
					pageSize: 10
				}
				getOwnPostImages(params).then((res => {
					this.albumList = res.data.rows
				}))
			},
			handleLogout() {
				this.$store.commit('logout');
				uni.removeStorageSync('token');
				uni.reLaunch({
					url: '/pages_sub/login/login'
				});
				this.showDrawer = false;
			},
			navigateTo(url, type) {
				if (!url || url.includes('placeholder')) {
					uni.showToast({
						title: '功能暂未开放',
						icon: 'none'
					});
					return;
				}
				if (type === 'my-qrcode') {
					this.showMyQRCode()
				} else {
					uni.navigateTo({
						url: url
					});
				}
				this.showDrawer = false;
			},
			// 跳转到我的二维码页面
			showMyQRCode() {
				this.showDrawer = false;
				// 确保用户信息存在，防止异常
				if (!this.userInfo || !this.userInfo.userId) {
					uni.showToast({
						title: '无法获取用户信息',
						icon: 'none'
					});
					return;
				}
				// 将用户信息对象转换为JSON字符串，并通过encodeURIComponent编码，以便在URL中安全传递
				const userInfoStr = encodeURIComponent(JSON.stringify(this.userInfo));

				// 使用uni.navigateTo跳转到二维码页面，并通过URL参数传递用户信息
				uni.navigateTo({
					url: `/pages_sub/user/qrcode/qrcode?user=${userInfoStr}`
				});
			},
			// 扫一扫功能
			onScanCode() {
				this.showDrawer = false;
				uni.scanCode({
					onlyFromCamera: true,
					scanType: ['qrCode'],
					success: (res) => {
						// 调用处理器，传入扫描结果和配置
						processScanResult(res.result);
					},
					fail: (err) => {
						// 仅处理非取消操作的失败
						if (err.errMsg !== 'scanCode:fail cancel') {
							uni.showToast({
								title: '扫码失败',
								icon: 'none'
							});
						}
					}
				});
			},
			handleTogglePublishPopup() {
				// 这里需要判断当前页面是否是活动页面，避免后台页面也响应事件
				const pages = getCurrentPages();
				const currentPage = pages[pages.length - 1];

				// 确保只有当前显示的页面才打开弹窗
				if (currentPage.route === 'pages/user/user') {
					this.showPublishPopup = !this.showPublishPopup;
				}
			},
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #F3F3F3;
		padding: 0 !important;
	}

	.page-content {
		position: relative;
	}

	.user-page-header {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: auto;
		z-index: 100;
		padding-top: var(--status-bar-height);
		background-color: transparent;
	}

	.man-add {
		position: fixed;



		right: 90rpx;
		top: 30rpx;

		// #ifdef MP-WEIXIN
		top: calc(var(--status-bar-height) + 260rpx);
		// #endif

		display: flex;
		align-items: center;
		background-color: rgba(255, 255, 255, .6);
		padding: 8rpx 10rpx;
		font-size: 20rpx;
		color: #ffffff;
		border-radius: 20rpx;

		.man-add-xfk {
			margin: 0 5rpx;
		}
	}

	.drawer-trigger {
		position: fixed;
		color: #ffffff;
		background-color: rgba(255, 255, 255, .6);
		border-radius: 50%;
		width: 48rpx;
		height: 48rpx;
		text-align: center;
		line-height: 48rpx;

		right: 25rpx;
		top: 30rpx;

		// #ifdef MP-WEIXIN
		top: calc(var(--status-bar-height) + 260rpx);
		// #endif

		z-index: 101;
	}

	.new-drawer-content {
		padding-top: calc(var(--status-bar-height) + 50rpx);
		display: flex;
		flex-direction: column;
		height: 100%;
		box-sizing: border-box;
		background-color: #f8f8f8;
	}

	.custom-cell-group {
		margin: 0 24rpx;
		background-color: #ffffff;
		border-radius: 16rpx;
		overflow: hidden;

		.custom-cell {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 28rpx 24rpx;
			position: relative; // 为了伪元素定位

			&:not(:last-child)::after {
				content: '';
				position: absolute;
				bottom: 0;
				left: 88rpx; // 与图标宽度+间距大致对齐
				right: 0;
				height: 1px;
				background-color: #f0f0f0;
				transform: scaleY(0.5);
			}

			&:active {
				background-color: #f9f9f9;
			}

			.cell-left {
				display: flex;
				align-items: center;

				.cell-icon {
					width: 40rpx; // 基础宽度
					height: 40rpx; // 基础高度
					line-height: 40rpx; // 确保垂直居中
					text-align: center; // 水平居中
					margin-right: 24rpx;
					font-size: 20px; // 默认图标大小
					color: #303133;
				}

				.cell-title {
					font-size: 30rpx;
					color: #303133;
				}
			}
		}
	}

	.separator {
		height: 1px;
		background-color: #f0f0f0;
		margin: 10rpx 30rpx;
	}


	.drawer-bottom-actions {
		display: flex;
		justify-content: space-around;
		align-items: center;
		padding: 20rpx 0;
		padding-bottom: calc(20rpx + constant(safe-area-inset-bottom));
		padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
		border-top: 1rpx solid #f0f0f0;
		background-color: #f8f8f8;
	}

	.action-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		flex: 1;
		padding: 10rpx 0;

		.userIconFont {
			background-color: #EFEEEE;
			width: 80rpx;
			height: 80rpx;
			line-height: 90rpx;
			font-size: 45rpx;
			border-radius: 50%;
			text-align: center;
		}

		.action-text {
			font-size: 24rpx;
			color: #606266;
			margin-top: 8rpx;
		}
	}
</style>